//
//  HomeViewController.m
//  ReceiptDelivery
//
//  Created by 吕晶 on 2020/6/29.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "HomeViewController.h"
#import "Home_NavBar.h"
#import "HomeWarningCell.h"
#import "HomeMenuModel.h"
#import "HomePendingCell.h"
#import "HomeNoticeCell.h"
#import "HomeYunShuMapCell.h"
#import "WCQRCodeScanningVC.h"
#import "ScanBoxModel.h"
#import "ScanZhuangXiangVC.h"
#import "HomeYunShuMapModel.h"
#import "HomeSearchVC.h"
#import "HomeMapVC.h"

@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource> {
    NSInteger total_warning;//预警总数
    NSInteger total_accept;//待受理总数
}

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) Home_NavBar *navBar;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <HomeMenuModel *>*warningArray;
@property (nonatomic, strong) NSMutableArray <HomeMenuModel *>*pendingArray;
@property (nonatomic, strong) HomeYunShuMapModel *mapModel;

@end

@implementation HomeViewController

-(HomeYunShuMapModel *)mapModel {
    if (!_mapModel) {
        _mapModel = [HomeYunShuMapModel new];
    }
    return _mapModel;
}

-(NSMutableArray<HomeMenuModel *> *)warningArray {
    if (!_warningArray) {
        _warningArray = [NSMutableArray array];
        HomeMenuModel *model1 = [HomeMenuModel new];
        model1.isMain = YES;
        model1.title = @"设备报警";
        model1.isWarning = YES;
        model1.count = 0;
        [_warningArray addObject:model1];
        
        HomeMenuModel *model2 = [HomeMenuModel new];
        model2.isMain = NO;
        model2.title = @"运单超时";
        model2.isWarning = YES;
        model2.count = 0;
        [_warningArray addObject:model2];
        
        HomeMenuModel *model3 = [HomeMenuModel new];
        model3.isMain = NO;
        model3.title = @"包装到期";
        model3.isWarning = YES;
        model3.count = 0;
        [_warningArray addObject:model3];
    }
    return _warningArray;
}

-(NSMutableArray<HomeMenuModel *> *)pendingArray {
    if (!_pendingArray) {
        _pendingArray = [NSMutableArray array];
        HomeMenuModel *model1 = [HomeMenuModel new];
        model1.isMain = YES;
        model1.title = @"受理";
        model1.count = 0;
        [_pendingArray addObject:model1];
        
        HomeMenuModel *model2 = [HomeMenuModel new];
        model2.isMain = NO;
        model2.title = @"回单确认";
        model2.count = 0;
        [_pendingArray addObject:model2];
        
        HomeMenuModel *model3 = [HomeMenuModel new];
        model3.isMain = NO;
        model3.title = @"运单签收";
        model3.count = 0;
        [_pendingArray addObject:model3];
    }
    return _pendingArray;
}

-(UIView *)bgView {
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, NaviHeight + 154)];
        _bgView.backgroundColor = Color_ThemeColor;
        [_bgView setRadianLayer:DXRadianDirectionBottom Radius:20];
    }
    return _bgView;
}

-(Home_NavBar *)navBar {
    if (!_navBar) {
        _navBar = [[Home_NavBar alloc] initWithFrame:CGRectMake(0, StatusBarHeight, ScreenW, 60)];
        __weak_self;
        _navBar.searchBlock = ^{
            //搜索
            HomeSearchVC *vc = [HomeSearchVC new];
            vc.hidesBottomBarWhenPushed = YES;
            [weakself.rt_navigationController pushViewController:vc animated:YES];
        };
        _navBar.scanBlock = ^{
            //扫一扫
            WCQRCodeScanningVC *vc = [WCQRCodeScanningVC new];
            vc.hidesBottomBarWhenPushed = YES;
            vc.returnBlock = ^(id dic) {
                ScanBoxModel *model = [ScanBoxModel mj_objectWithKeyValues:dic];
                if (model.type.length) {
                    ScanZhuangXiangVC *vc = [ScanZhuangXiangVC new];
                    vc.boxModel = model;
                    vc.hidesBottomBarWhenPushed = YES;
                    [weakself.rt_navigationController pushViewController:vc animated:YES];
                }
            };
            [weakself.rt_navigationController pushViewController:vc animated:YES];
        };
//        _navBar.billBlock = ^{
//            //运单查询
//        };
//        _navBar.packageBlock = ^{
//            //包装查询
//        };
//        _navBar.storageBlock = ^{
//            //库存查询
//        };
//        _navBar.boardBlock = ^{
//            //系统看板
//        };
    }
    return _navBar;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.navBar.nim_bottom, ScreenW, ScreenH - (self.navBar.nim_bottom) - TabbarHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        __weak_self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakself requestForData];
        }];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    total_warning = 0;
    total_accept = 0;
    [self.view addSubview:self.bgView];
    [self.view addSubview:self.navBar];
    [self.view addSubview:self.tableView];
    [self requestForData];
}

//判断是否需要更新
-(void)judgeNeedUpdate {
    //https://apps.apple.com/us/app/云货主/id1540908637
    NSURL *url = [NSURL URLWithString:@"http://itunes.apple.com/lookup?id=1540908637"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                       timeoutInterval:10];
    
    [request setHTTPMethod:@"POST"];
    NSOperationQueue *queue = [NSOperationQueue new];
    __weak_self;
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response,NSData *data,NSError *error){
        NSMutableDictionary *receiveStatusDic=[[NSMutableDictionary alloc]init];
        if (data) {
            NSDictionary *receiveDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            if ([[receiveDic valueForKey:@"resultCount"] intValue]>0) {
                [receiveStatusDic setValue:@"1" forKey:@"status"];
                [receiveStatusDic setValue:[[[receiveDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"version"]   forKey:@"version"];
            }else{
                [receiveStatusDic setValue:@"-1" forKey:@"status"];
            }
        }else{
            [receiveStatusDic setValue:@"-1" forKey:@"status"];
        }
        NSString *appstoreVersion = [receiveStatusDic valueForKey:@"version"];
        NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
        NSString *currentVersion = [infoDic valueForKey:@"CFBundleShortVersionString"];
        if ([appstoreVersion compare:currentVersion options:NSNumericSearch] == NSOrderedDescending) {
            //需要更新
            NSLog(@"需要更新");
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"已检测到新版本，请前往更新" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"前往" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    NSString *urlStr = [NSString stringWithFormat: @"itms-apps://itunes.apple.com/app/id%@?mt=8",@"1540908637"];
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr] options:@{} completionHandler:nil];
                }];
                UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alert addAction:sureAction];
                [alert addAction:cancleAction];
                [weakself presentViewController:alert animated:YES completion:nil];
            });
        }else {
            //不需要更新
            NSLog(@"不需要更新");
        }
    }];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestForData];
    [self judgeNeedUpdate];
}

- (void)requestForData {
    [HttpRequest PostWithApi:ReceiptDeliveryHomeData params:@{} progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.warningArray[0].count = [[responseObject objectForKey:@"warning"] integerValue];
            if (self.warningArray[0].count) {
                self.warningArray[0].isMain = YES;
            }else {
                self.warningArray[0].isMain = NO;
            }
            self.warningArray[1].count = [[responseObject objectForKey:@"overtime_num"] integerValue];
            if (self.warningArray[1].count) {
                self.warningArray[1].isMain = YES;
            }else {
                self.warningArray[1].isMain = NO;
            }
            self.warningArray[2].count = [[responseObject objectForKey:@"past_num"] integerValue];
            if (self.warningArray[2].count) {
                self.warningArray[2].isMain = YES;
            }else {
                self.warningArray[2].isMain = NO;
            }
            
            self->total_warning = [[responseObject objectForKey:@"total_warning"] integerValue];
            
            self.pendingArray[0].count = [[responseObject objectForKey:@"accept_num"] integerValue];
            if (self.pendingArray[0].count) {
                self.pendingArray[0].isMain = YES;
            }else {
                self.pendingArray[0].isMain = NO;
            }
            self.pendingArray[1].count = [[responseObject objectForKey:@"affirm_num"] integerValue];
            if (self.pendingArray[1].count) {
                self.pendingArray[1].isMain = YES;
            }else {
                self.pendingArray[1].isMain = NO;
            }
            self.pendingArray[2].count = [[responseObject objectForKey:@"sign_num"] integerValue];
            if (self.pendingArray[2].count) {
                self.pendingArray[2].isMain = YES;
            }else {
                self.pendingArray[2].isMain = NO;
            }
            
            self->total_accept = [[responseObject objectForKey:@"total_accept"] integerValue];
            
            self.mapModel = [HomeYunShuMapModel mj_objectWithKeyValues:responseObject];
            
            [self.tableView reloadData];
        }
        [self.tableView.mj_header endRefreshing];
    } fail:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        HomeWarningCell *cell = [HomeWarningCell HomeWarningCellWithTableView:tableView];
        cell.warningArray = self.warningArray;
        cell.total_warning = total_warning;
        return cell;
    }else if (indexPath.section == 1) {
        HomePendingCell *cell = [HomePendingCell HomePendingCellWithTableView:tableView];
        cell.pendingArray = self.pendingArray;
        cell.total_accept = total_accept;
        //受理、回单确认-我发运的
        //运单签收-我收的
        return cell;
    }else if (indexPath.section == 2) {
        HomeYunShuMapCell *cell = [HomeYunShuMapCell HomeYunShuMapCellWithTableView:tableView];
        cell.model = self.mapModel;
        return cell;
    }
    UITableViewCell *cell = [UITableViewCell new];
    return cell;
//    else if (indexPath.section == 2) {
//        HomeNoticeCell *cell = [HomeNoticeCell HomeNoticeCellWithTableView:tableView];
//        cell.noticeText = @"一条公告一条公告一条公告一条公告一条公告一条公告一条公告一条公告一告一条公告一条公告一条公告一条公告一条公告一";
//        return cell;
//    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        HomeWarningCell *cell = [HomeWarningCell HomeWarningCellWithTableView:tableView];
        return cell.height;
    }else if (indexPath.section == 1) {
        HomePendingCell *cell = [HomePendingCell HomePendingCellWithTableView:tableView];
        return cell.height;
    }else if (indexPath.section == 2) {
        HomeYunShuMapCell *cell = [HomeYunShuMapCell HomeYunShuMapCellWithTableView:tableView];
        return cell.height;
    }
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2) {
        HomeMapVC *vc = [HomeMapVC new];
        vc.hidesBottomBarWhenPushed = YES;
        vc.model = self.mapModel;
        [self.rt_navigationController pushViewController:vc animated:YES];
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
